<template>
  <teleport to="#modelLogin">
    <div class="fixed-right-0 top-0 bottom-0 w-0 z-10">
      <div class="absolute right-0 bottom-25 pr-3">
        <div class="flex justify-center items-center mb-3">
          <div
            @click="opencart"
            class="dioa-center justify-center items-center flex w-[54px] h-[54px] rounded-[100%] bg-white p-[1px] cursor-pointer shadow-lg group lg:w-10 lg:h-10"
          >
            <div
              class="dioa-center justify-center items-center group-hover:bg-neutral-20 transition-background flex w-full h-full rounded-[100%]"
            >
              <span class="dioa-badge__root relative inline-flex">
                <!-- <div
                  class="dioa-badge__content absolute z-1 flex justify-center items-center data-position-t:top-0 data-position-b:bottom-0 data-position-l:left-0 data-position-r:right-0 px-[6px] min-w-[18px] min-h-[18px] text-center text-sm text-white rounded-full data-position-t:-translate-y-1/2 data-position-b:translate-y-1/2 data-position-l:translate-x-[calc(-100%+8px)] data-position-r:translate-x-[calc(100%-8px)] bg-red"
                  data-position-t=""
                  data-position-r=""
                >
                  13
                </div> -->
                <svg
                  viewBox="0 0 24 24"
                  width="24"
                  height="24"
                  class="dioa-icon lg:w-5 lg:h-5"
                >
                  <path
                    d="M4.132 3.805q-.016-.07-.044-.137-.028-.066-.066-.126-.039-.06-.087-.114-.048-.054-.104-.098-.056-.045-.12-.08-.062-.034-.13-.058-.068-.023-.139-.035-.07-.012-.142-.012-.1 0-.196.023-.07.016-.136.044-.066.028-.126.066-.061.039-.114.087-.054.048-.098.104-.045.056-.08.12-.034.062-.058.13-.023.068-.035.138-.012.071-.012.143 0 .1.022.195l2.404 10.233q.204.87.906 1.426.7.556 1.595.556h9.25q.911 0 1.62-.575.707-.576.894-1.468l.997-4.765q.25-1.197-.52-2.146-.772-.95-1.995-.95H5.157q-.195 0-.37.085l-.655-2.786Zm1.036 4.411 1.368 5.82q.068.292.302.478.235.186.534.186h9.25q.304 0 .54-.193.238-.192.3-.49l.997-4.765q.084-.4-.174-.718-.258-.318-.667-.318H5.168Z"
                    fill-rule="evenodd"
                    fill="currentColor"
                  ></path>
                  <circle cx="7.616" cy="18.676" fill="currentColor" r="1.286"></circle>
                  <circle
                    cx="16.386"
                    cy="18.676"
                    fill="currentColor"
                    r="1.286"
                  ></circle></svg
              ></span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="cart" v-if="isCart">
      <div class="cartLayer">
        <el-container>
          <el-header
            >购物车
            <div class="closeBtn">
              <el-button @click="handleClose" circle
                ><i class="iconfont">&#xe60e;</i></el-button
              >
            </div>
          </el-header>
          <el-main class="main">
            <template v-if="cartList.length > 0">
              <div v-for="item in cartList" :key="item.id" class="item">
                <div class="infoitem">
                  <input
                    type="checkbox"
                    v-model="item.checked"
                    @change="calculateTotal"
                  />
                  <img :src="item.picUrl" alt="" />
                  <div>
                    <h3>{{ item.spuName }}</h3>
                    <p>
                      <el-tag type="danger" size="small">{{ item.skuName }}</el-tag>
                    </p>
                    <div>
                      <span class="red">{{ item.addPrice }}</span
                      >元
                    </div>
                  </div>
                </div>
                <el-button circle link @click="delItem(item)">
                  <el-icon :size="20"><Delete /></el-icon>
                </el-button>
              </div>
            </template>
            <el-empty description="暂无数据" v-else></el-empty>
          </el-main>
          <el-footer height="120">
            <div class="selectall">
              <button @click="checkAll = !checkAll">全选/反选</button>
              <div class="calcPrice">
                总价: <span>{{ totalPrice }}</span
                >元
              </div>
            </div>
            <button
              style="margin-bottom: 20px"
              @click="submitCart"
              type="button"
              class="dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed data-loading:text-transparent h-14 px-10 text-lg font-medium text-white bg-red hover:bg-neutral-60 active:bg-black disabled:bg-neutral-40 rounded-full border-0 w-full"
            >
              立即购买
            </button>
          </el-footer>
        </el-container>
      </div>
    </div>
  </teleport>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { getCarts, removeCarts } from "@/common/userApi";
import { CartItem } from "@/common/utils/userType";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { userorderStore } from "@/store/orderStore";
const orderStore = userorderStore();

const routerpush = useRouter();
// 打开购物车
const isCart = ref(false);
const opencart = () => {
  isCart.value = true;
  getcartList();
};
const handleClose = () => {
  isCart.value = false;
};

// 获取购物车列表getCarts
const cartList = ref<CartItem | any>([]);
const cartSelect = ref<CartItem | any>([]);

const getcartList = () => {
  getCarts().then((result) => {
    if (result.rows.length > 0) {
      result.rows.forEach((element) => {
        element.checked = false;
      });
    }
    cartList.value = result.rows;
  });
};

const checkAll = ref(false);
const totalPrice = ref(0);

// 计算总价
function calculateTotal() {
  let priceSum = 0;
  console.log(cartList.value);
  cartList.value.forEach((item) => {
    if (item.checked) {
      priceSum += item.addPrice * item.quantity;
      cartSelect.value.push(item);
    } else {
      cartSelect.value = cartSelect.value.filter((item) => item.checked == false);
    }
  });
  totalPrice.value = priceSum;
}

// 提交购物车

function submitCart() {
  // 这里可以添加提交购物车的逻辑
  const selectedItems = cartList.value.filter((item: any) => item.checked);
  if (selectedItems.length > 0) {
    console.log("选中的商品:", selectedItems);
    const datapost = {
      orderType: "1",
      orderAmount: totalPrice.value + "",
      payType: "1",
      itemBos: [] as any,
    } as any;
    selectedItems.forEach((element: any) => {
      let data = {
        itemType: "1",
        itemId: element.skuId,
        priceId: element.priceId,
        itemName: element.skuName,
        itemAmount: element.addPrice,
        quantity: 1,
        baseAmount: element.addPrice,
        thumbnailUrl: element.picUrl,
      };
      datapost.itemBos.push(data);
    });
    console.log(datapost);
    localStorage.setItem("orderData", JSON.stringify(datapost));
    orderStore.updataPostOrderData(datapost);
    routerpush.push({ name: "buy" });
    handleClose();
  } else {
    ElMessage.error("您还没有选中商品");
  }
}
// 删除购物车delItem
const delItem = (item: CartItem) => {
  removeCarts(item.id).then((result) => {
    if (result.code == 200) {
      getcartList();
      ElMessage({
        message: "删除成功",
        type: "success",
        plain: true,
      });
    }
  });
};

// 监听checkAll变化来设置全选或全不选
watch(
  () => checkAll,
  (newValue) => {
    console.log(newValue, "监控数据");
    cartList.value.forEach((item) => {
      item.checked = newValue;
    });
    calculateTotal();
  }
);
// 初始计算总价
calculateTotal();
</script>

<style lang="scss" scoped>
.cart {
  position: fixed;
  z-index: 2000;
  right: 0px;
  bottom: 0px;
  top: 0;
  left: 0;
  background: rgb(0 0 0 / 42%);
  .cartLayer {
    width: 500px;
    height: 100%;
    background: #fff;
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
  }
}
.el-header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  position: relative;
  .closeBtn {
    position: absolute;
    right: 20px;
  }
}
.main {
  height: calc(100vh - 160px);
  background: #f8f8f8;
}
.item {
  display: flex;
  justify-content: space-between;
  background: #fff;
  margin: 10px 0;
  padding: 10px;
  border-radius: 5px;
  cursor: pointer;
  .infoitem {
    display: flex;
    img {
      width: 80px;
      height: 80px;
      margin: 0 10px;
    }
    h3 {
      font-size: 16px;
      margin-bottom: 5px;
    }
    p {
      margin-bottom: 5px;
    }
  }

  .red {
    color: red;
    font-weight: bold;
  }
}
.selectall {
  display: flex;
  padding: 10px;
  font-size: 16px;
  justify-content: space-between;
  .calcPrice {
    span {
      color: red;
      font-weight: bold;
    }
  }
}
</style>
